/** 
* 留言action类
* 
* @author  周郎(zhoulang),web@zhoulang.net
* @link http://www.zhoulang.net
* @version syuebook v1.0
* @Copyright 2009 syue.com, Inc. All rights reserved.
* @since   JDK1.6
*/  

package net.zhoulang.dao;

import java.util.List;
import java.sql.SQLException;
import net.zhoulang.entity.BookEntity;
import net.zhoulang.idal.IBook;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
/**
 *留言数据层
 * @author zhoulang
 */
@org.springframework.transaction.annotation.Transactional
public class BookDao extends HibernateDaoSupport implements IBook {
    /**
     * 添加留言信息
     * @param entity
     * @return Integer
     */
    public int bookAdd(BookEntity entity) {
        getHibernateTemplate().save(entity);
        return entity.getBookid();
    }
    /**
     * 修改留言
     * @param entity
     */
    public void bookUpdate(BookEntity entity) {
        getHibernateTemplate().saveOrUpdate(entity);
    }
    /**
     * 删除留言
     * @param entity
     */
    public void bookDel(final int id) {
    	Object entity = getHibernateTemplate().get(BookEntity.class, id);
    	getHibernateTemplate().delete(entity);
    }
    /**
     * 获取留言总数
     * @return Integer
     */
    @SuppressWarnings("unchecked")
	public int getBookCount() {
    	List list = getHibernateTemplate().executeFind(new HibernateCallback(){
    		public Object doInHibernate(Session session) throws HibernateException, SQLException {
    			Query query = session.createQuery("select count(*) from BookEntity");
    			return query.list();
    		}
    	});
    	return Integer.parseInt(list.get(0) + "");
    }
    /**
     * 获取留言总数
     * @return Integer
     */
    @SuppressWarnings("unchecked")
	public List<BookEntity> getBookList(int page, final int size) {
        if(page <= 0) {
            page = 1;
        }
        final int curPage = page;

        List list = getHibernateTemplate().executeFind(new HibernateCallback() {
           public Object doInHibernate(Session session) throws HibernateException, SQLException {
               Query query = session.createQuery("from BookEntity");
               List result = query.setFirstResult((curPage -1) * size).setMaxResults(size).list();
               return result;
           }
        });

        return list;
    }
}
